package com.project.easy.common.framework.web.service.impl.login;

import com.project.easy.common.framework.auth.core.ITokenStore;
import com.project.easy.common.framework.auth.dto.TokenContext;
import  com.project.easy.common.util.string.StringUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author GreatorMan.cool
 * @copyright: Copyright (c) 2020
 * @company: 扬起科技有限公司
 * @date 2021/11/1 21:44
 * @description: 内存存储TOKEN
 */
@ConditionalOnProperty(prefix = "yqkj.user.login",  name = "persistence", matchIfMissing = false, havingValue = "memor")
@Component
public class MemorTokenStore implements ITokenStore {
    /**
     * TOKEN 存储数据
     */
    private  static final Map<String, TokenContext> TOKEN_MAP = new ConcurrentHashMap<String, TokenContext>();

    private  static final Map<String, String> ACC_TOKEN_MAP = new ConcurrentHashMap<>();


    @Override
    public Boolean remove(String token) {
       TOKEN_MAP.remove(token);
       return Boolean.TRUE;
    }

    @Override
    public Boolean saveToken(TokenContext userInfo) {
        if (ACC_TOKEN_MAP.containsKey(userInfo.getUserInfo().getAcc())) {
            String token = ACC_TOKEN_MAP.get(userInfo.getUserInfo().getAcc());
            this.remove(token);
        }
        if (StringUtil.isNotBlank(userInfo.getToken())) {
            ACC_TOKEN_MAP.put(userInfo.getUserInfo().getAcc(), userInfo.getToken());
            TOKEN_MAP.put(userInfo.getToken(), userInfo);
            return Boolean.TRUE;
        }
        return Boolean.FALSE;
    }

    @Override
    public Boolean validata(String token) {
        return TOKEN_MAP.containsKey(token);
    }

    @Override
    public TokenContext queryUserInfo(String token) {
        return TOKEN_MAP.get(token);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
